//
//  ViewController.swift
//  swift-servers
//
//  Created by huang on 16/5/20.
//  Copyright © 2016年 llj. All rights reserved.
//

import UIKit
import Swifter
import FMDB


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //创建、连接数据库
        let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
        let fileURL = documents.URLByAppendingPathComponent("test.sqlite")
        
        let database = FMDatabase(path: fileURL.path)
        
        if !database.open() {
            print("Unable to open database")
            return
        }
        
        
        do {
            let server = HttpServer()
            
            //接口1
            server["/hello"] = { r in return .OK(.Html("You asked for ")) }
            
            //接口2
            server["/json"] = { r in
                let jsonObject: NSDictionary = [NSString(string: "foo"): NSNumber(int: 3), NSString(string: "bar"): NSString(string: "baz")]
                return .OK(.Json(jsonObject))
            }
            
            //接口3
            server.GET["/login"] = { r in
                let lljqueryParams: [(String, String)] = r.queryParams
                let params = lljqueryParams[0]
                var name = ""
                var pass = ""
                do {
                    //第一次创建表
                    //try database.executeUpdate("create table test1(name text, pass text)", values: nil)
                    try database.executeUpdate("insert into test1 (name, pass) values (?, ?)", values: [params.0, params.1])
                    
                    let rs = try database.executeQuery("select name, pass from test1", values: nil)
                    
                    while rs.next() {
                        name = rs.stringForColumn("name")
                        pass = rs.stringForColumn("pass")
                        
                    }
                    
                }catch let error as NSError {
                    print("failed: \(error.localizedDescription)")
                }
                
                //关闭数据库
                //database.close()
                
                //返回页面数据
                return .OK(.Html("\(name)++\(pass)+++\n++++\(lljqueryParams)"))
                
            }
            
            
            try server.start(9080)
        }catch {
            print("Server start error: \(error)")
        }
        
        
        
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

